#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/time.h>

#include "perror_exit.h"

char *cat(const char *fmt, ...) {
	va_list ap;
	int d;
	char *s = NULL;
	char *msg = strdup("");
	char tmp[32];

	assert(fmt != NULL);
	
	va_start(ap, fmt);
	while(*fmt) {
		switch(*fmt) {
		case '%':
			++fmt;
			switch(*fmt) {
			case 's':
				s = va_arg(ap, char *);
				break;
			case 'd':
				d = va_arg(ap, int);
				snprintf(tmp,32,"%d",d);
				s = &(tmp[0]);
				break;
			case 'c':
				d = va_arg(ap, int);
				snprintf(tmp,32,"%d",(int)d);
				s = &(tmp[0]);
			}
			break;
		default:
			snprintf(tmp,32,"%c",*fmt);
			s = &(tmp[0]);
		}
		if(!(msg = (char *)realloc(msg,sizeof(char)*(strlen(msg)+strlen(s)+1)))) {
			perror("malloc()");
			abort();
		}
		strcat(msg,s);
		va_end(ap);
		++fmt;
	}
	return msg;
}

char *
chomp(char *string)
{
	char *ptr;
	if(ptr = strrchr(string,'\n'))
		*ptr = '\0';
	return string;
}

void
time_it (void)
{
  static unsigned long int iteration = 0;
  static struct timeval then = { 0, 0 };
  struct timeval now = { 0, 0 };
  long difference;

  if (then.tv_sec == 0) {
	 gettimeofday (&then, NULL);
	 return;
  }

  gettimeofday (&now, NULL);

  if (now.tv_usec < then.tv_usec) {
	 now.tv_sec -= 1;
	 now.tv_usec += 1000000;
  }

  difference =
	 (now.tv_sec - then.tv_sec) * 1000000 + (now.tv_usec - then.tv_usec);

  fprintf (stderr,"%d\t%d\n", ++iteration, difference);

  then.tv_sec = 0;
  then.tv_usec = 0;

}
